package vn.vfriends.id.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import vn.vfriends.id.bean.RoleBean;
import vn.vfriends.id.jpa.entity.Role;

/**
 *
 * @author tuan@vfriends.vn
 */
@FacesConverter(value = "roleConverter")
public class RoleConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String name) {
        if (name == null || name.length() == 0) {
            return null;
        }
        RoleBean bean = (RoleBean) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "roleBean");
        if (bean == null) {
            return null;
        }
        return bean.getRole(name);
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Role) {
            Role role = (Role) object;
            return role.getName();
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: vn.vfriends.id.jpa.entity.SysRole");
        }
    }
}